﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DoubleH.Utility.Configuration;
using System.Diagnostics;
using System.Xml;
using Table = FCNS.Data.Table;
using System.Collections.ObjectModel;

namespace DoubleH.Utility.Login
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow : Window
    {
        public LoginWindow()
        {
            InitializeComponent();
        }

        public void Init(Table.UserS.EnumFlag flag)
        {
            InitVar();
            InitEvent();
            UpdateSoft();
            NormalUtility.LoadTabTip();
        }

        bool configSql = false;
        ObservableCollection<Table.UserS> allUserS = null;

        private void UpdateSoft()
        {
            if (!DoubleHConfig.AppConfig.CheckUpdate)//如果服务器链接慢的话，就会卡住窗体显示的慢了。关闭就快很多。
                return;

            string oldVer = labelVersion.Content.ToString().Remove(0, 6);
            Func<string, string, string> func = DoubleH.Utility.IO.FileTools.CheckVerByAssembly;
            string str = func.Invoke(FCNS.Data.DbDefine.updateUrl, oldVer);
            if (!string.IsNullOrEmpty(str))
            {
                labelContact.Content = "新版本：" + str + " 已发布，请下载更新。";
                labelContact.Foreground = Brushes.Red;
            }
        }

        private void InitVar()
        {
            //初始化数据库
            if (DoubleHConfig.AppConfig.DataConfigItems.Count == 0)
            {
                DoubleHConfig.AppConfig.DataConfigItems.Add(new DataConfig()
                {
                    DataType = FCNS.Data.DataType.SQLITE.ToString(),
                    Flag = FCNS.Data.DataType.SQLITE.ToString(),
                    DataAddress = FCNS.Data.DbDefine.dbFile
                });
            }
            comboBoxData.ItemsSource = DoubleHConfig.AppConfig.DataConfigItems;
            comboBoxData.DisplayMemberPath = "Flag";
            comboBoxData.Text = DoubleHConfig.AppConfig.DataFlag;
            if (comboBoxData.SelectedItem == null)
                comboBoxData.SelectedIndex = 0;

            DataConfig dc = comboBoxData.SelectedItem as DataConfig;
            Debug.Assert(dc != null);
            try
            {
                if (Net.NetUtility.TestConnection(dc))
                    InitSqlData(dc);
                else
                    MessageWindow.Show("数据库连接失败,请检查数据库配置信息或增大超时值再尝试.");
            }
            catch (Exception ee)
            {
                Table.ErrorS.WriteLogFile("数据库连接错误,登录窗体无法初始化数据库. -> " + ee.Message);
                MessageWindow.Show("无法连接数据库");
                buttonLogin.IsEnabled = false;
            }

            this.Title = FCNS.Data.DbDefine.SystemName + " - 用户登录";
            labelDbVer.Content += FCNS.Data.DbDefine.dbVer;

            string verNow = this.GetType().Assembly.GetName().Version.ToString();
            FileVersionInfo info = FileVersionInfo.GetVersionInfo(FCNS.Data.DbDefine.baseDir + "DoubleH.Utility.dll");
            labelVersion.Content += (verNow.Remove(verNow.Length - 1) + info.FileMinorPart.ToString() + info.FileBuildPart.ToString() + info.FilePrivatePart.ToString());

            textBoxPwd.Focus();
            this.Width -= 468;
            //255  715
            groupBoxDataFlag.Visibility = Visibility.Collapsed;
        }

        private void InitEvent()
        {
                buttonConfig.Click+= (ss, ee) => ShowSqlConfigControls();
                        this.Closed += (ss, ee) => SaveSqlConfig();
            comboBoxData.SelectionChanged += (ss, ee) => ComboBoxDataSelectionChanged();
            labelContact.MouseUp += (ss, ee) => System.Diagnostics.Process.Start("http://www.fcnsoft.com/download/readme.txt");
            labelVersion.MouseDoubleClick += (ss, ee) => ShowSql();
            buttonLogin.Click += (ss, ee) => Login();
        }

        private void Login()
        {
            SaveSqlConfig();
            UserLogin();
        }

        private void ComboBoxDataSelectionChanged()
        {
            DoubleHConfig.AppConfig.DataFlag = ((DataConfig)comboBoxData.SelectedItem).Flag;
            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);
            if (System.IO.File.Exists("DoubleH.exe"))
                System.Diagnostics.Process.Start("DoubleH.exe");
            else if (System.IO.File.Exists("DHserver.exe"))
                System.Diagnostics.Process.Start("DHserver.exe");

            System.Environment.Exit(0);
        }

        private void ShowSqlConfigControls()
        {
            if (!groupBoxDataFlag.IsEnabled )
            {
                configSql = true;
                groupBoxDataFlag.IsEnabled = true;
                this.Width +=468;
                groupBoxDataFlag.Visibility = Visibility.Visible;
            }
        } 

        private void InitSqlData(DataConfig dc)
        {
            FCNS.Data.SQLdata.SqlConfig = new FCNS.Data.SQLdata.SqlString((FCNS.Data.DataType)Enum.Parse(typeof(FCNS.Data.DataType), dc.DataType), dc.DataAddress, dc.DataName,
             dc.Port, dc.DataUser, dc.DataPassword, dc.TimeOut,dc.HttpPort);

            allUserS = Table.UserS.GetLoginUserForDoubleH();
            textBoxName.Text = dc.LastName;
        }

        private void SaveSqlConfig()
        {
            if (configSql)
                ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);

            configSql = false;//没有这个的话，当用户登录失败，就会重复保存了。
        }

        private void UserLogin()
        {
            if (Table.SysConfig.SysConfigParams.CompanyName != "台山市新天地数码科技有限公司")
            {
                if (Table.SysConfig.SysConfigParams.Ver != FCNS.Data.DbDefine.dbVer)
                {
                    if (MessageWindow.Show("数据库版本不一致,禁止登陆.", "点击‘确定’更新系统补丁......", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                        System.Diagnostics.Process.Start(FCNS.Data.DbDefine.baseDir + "update.exe");

                    return;
                }
            }
            if (DateTime.Now.Date < Table.SysConfig.SysConfigParams.LastLoginDate.Date)
            {
                if (Table.SysConfig.SysConfigParams.ForceVerificationDate)
                {
                    MessageWindow.Show("当前日期小于上一次登录的日期,禁止登录.");
                    return;
                }
                if (MessageWindow.Show("", "当前日期小于上一次登录的日期：" + Table.SysConfig.SysConfigParams.LastLoginDate.ToLongDateString() + "，继续吗？", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;//还要检查是否月结日
            }

            Table.UserS selectedUserS = allUserS.FirstOrDefault(f => f.UserNO == textBoxName.Text);
            if (selectedUserS == null||selectedUserS.Password!=textBoxPwd.Password)
            {
                MessageWindow.Show("用户名或密码错误");
                textBoxPwd.Clear();
                textBoxPwd.Focus();
                return;
            }

            (comboBoxData.SelectedItem as DataConfig).LastName = textBoxName.Text;
            DoubleHConfig.AppConfig.DataFlag = comboBoxData.Text;
            textBoxPwd.Clear();//清空,当用户注销的时候就看不到密码了
            Table.UserS.LoginUser = selectedUserS;
            DoubleHConfig.UserConfig = ConfigSerializer.LoadUserConfig(Table.UserS.LoginUser.Id);
            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);
            Table.SysConfig.SysConfigParams.UpdateLastLoginDate(DateTime.Now);
            this.Close();
        }

        private void ShowSql()
        {
            TextInputWindow tiw = new TextInputWindow();
            tiw.Init("请输入数据库密码", string.Empty, true);
            tiw.ShowDialog();
            if (tiw.GetText != FCNS.Data.SQLdata.SqlConfig.Password)
                return;

            SqlWindow sw = new SqlWindow();
            sw.ShowDialog();
        }
    }
}